<template>
  <div>
    <el-container style="flex-wrap: wrap;">
      <!-- 头部导航栏 -->
      <BreadHeader></BreadHeader>
      <XPannel>
        <template v-slot:header>
          <span>权限管理</span>
          <el-button
            type="primary"
            style="float: right; padding: 10px 20px; margin-left: 15px"
            @click="draweradd = true"
            >添加</el-button
          >
          <!-- 添加权限的抽屉 -->
          <el-drawer
            title="添加权限"
            :visible.sync="draweradd"
            ref="drawer_add"
            :show-close="true"
            style="text-align: center"
          >
            <el-form
              :model="addruleForm"
              :rules="rulesadd"
              ref="addruleForm"
              label-width="100px"
              class="demo-ruleForm"
              style="text-align: center"
            >
              <el-form-item
                label="权限名称"
                prop="addname"
                style="margin: 20px; width: 80%; margin: 20px auto"
              >
                <el-input
                  placeholder="请输入权限名称"
                  v-model="addruleForm.addname"
                  clearable
                  style="width: 300px"
                >
                </el-input>
              </el-form-item>
              <el-form-item
                label="层级"
                prop="level"
                style="margin: 20px; width: 80%; margin: 20px auto"
              >
                <el-select
                  v-model="addruleForm.level"
                  placeholder="请选择层级"
                  style="width: 300px"
                >
                  <el-option
                    v-for="(item, index) in options"
                    :key="index"
                    :label="item.level"
                    :value="item.level"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                label="父级"
                prop="father"
                style="margin: 20px; width: 80%; margin: 20px auto"
              >
                <el-select
                  v-model="addruleForm.father"
                  placeholder="请选择父级"
                  style="width: 300px"
                >
                  <el-option
                    v-for="(item, index) in options"
                    :key="index"
                    :label="item.father"
                    :value="item.father"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                label="描述"
                prop="adddescription"
                style="margin: 20px; width: 80%; margin: 20px auto"
              >
                <el-input
                  type="textarea"
                  placeholder="请输入权限描述"
                  v-model="addruleForm.adddescription"
                  clearable
                  style="width: 300px"
                  rows="5"
                  cols="25"
                >
                </el-input>
              </el-form-item>
              <el-button
                type="primary"
                @click="addallocation('addruleForm')"
                style="padding: 10px 20px; margin-right: 5px"
                >保存</el-button
              >
              <el-button
                type="info"
                @click="resetForm('addruleForm')"
                style="padding: 10px 20px; margin: 5px; margin-right: 50px"
                >重置</el-button
              >
            </el-form>
            <!-- 对话框底部 -->
            <!-- <div slot="footer" class="dialog-footer"> -->

            <!-- </div> -->
          </el-drawer>
          <!-- </el-dialog> -->
        </template>
        <template v-slot:default>
          <!-- 搜索 -->
          <el-row style="margin: 5px 0">
            <el-col :span="1.8" style="padding: 0 0">
              <template>
                <p style="color: #303133; font-size: 16px; line-height: 40px">
                  权限名称：
                </p>
              </template>
            </el-col>
            <el-col :span="4" style="padding: 0 0; margin: 0 10px">
              <el-input v-model="searchname" clearable> </el-input>
            </el-col>
            <el-col :span="2" style="margin-left: 15px">
              <el-button
                type="primary"
                @click="searchroles"
                style="padding: 12px 15px"
              >
                <i class="el-icon-search"></i>搜索
              </el-button>
            </el-col>
          </el-row>
          <!-- 列表 -->
          <el-table
            :data="allocation_list"
            @selection-change="handleSelectionChange"
            ref="multipleTable"
            height="450"
            border
            style="width: 100%; margin: 20px auto"
          >
            <el-table-column label="全选" type="selection" width="55">
            </el-table-column>
            <el-table-column prop="id" label="ID" width="100">
            </el-table-column>
            <el-table-column prop="name" label="权限名称" width="200">
            </el-table-column>
            <el-table-column prop="level" label="层级" width="200">
            </el-table-column>
            <el-table-column prop="description" label="权限说明" width="180">
            </el-table-column>
            <el-table-column prop="father" label="父级ID" width="200">
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button
                  @click="authorize(scope)"
                  type="warning"
                  style="margin-left: 16px; padding: 5px 10px"
                >
                  <i class="el-icon-setting"></i>
                  批量授权
                </el-button>
                <el-button
                  @click="xiugaiobtain(scope.row)"
                  type="primary"
                  style="margin-left: 16px; padding: 5px 10px"
                >
                  <i class="el-icon-edit"></i>
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  @click="open(scope.row)"
                  style="padding: 5px 10px"
                >
                  <i class="el-icon-delete"></i>
                  删除
                </el-button>
                <!-- 编辑权限--抽屉 -->
                <el-drawer
                  title="编辑权限"
                  :visible.sync="drawer"
                  :show-close="true"
                >
                  <el-form
                    :model="edutruleForm"
                    :rules="rulesedit"
                    ref="edutruleForm"
                    label-width="100px"
                    class="demo-ruleForm"
                    style="text-align: center;"
                  >
                    <el-form-item
                      label="权限名"
                      prop="name"
                      style="margin: 20px; width: 80%; margin: 20px auto"
                    >
                      <el-input
                        placeholder="请输入权限名称"
                        v-model="edutruleForm.name"
                        clearable
                        style="width: 300px"
                      >
                      </el-input>
                    </el-form-item>
                    <el-form-item
                      label="层级"
                      prop="level"
                      style="margin: 20px; width: 80%; margin: 20px auto"
                    >
                      <el-select
                        v-model="edutruleForm.level"
                        placeholder="请选择"
                        style="width: 300px"
                      >
                        <el-option
                          v-for="(item, index) in options"
                          :key="index"
                          :label="item.level"
                          :value="item.level"
                        >
                        </el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item
                      label="父级"
                      prop="father"
                      style="margin: 20px; width: 80%; margin: 20px auto"
                    >
                      <el-select
                        v-model="edutruleForm.father"
                        placeholder="请选择父级"
                        style="width: 300px"
                      >
                        <el-option
                          v-for="(item, index) in options"
                          :key="index"
                          :label="item.father"
                          :value="item.father"
                        >
                        </el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item
                      label="描述"
                      prop="descriptionsave"
                      style="margin: 20px; width: 80%; margin: 20px auto"
                    >
                      <el-input
                        type="textarea"
                        placeholder="请输入权限名称"
                        v-model="edutruleForm.descriptionsave"
                        clearable
                        style="width: 300px"
                        rows="5"
                        cols="25"
                      >
                      </el-input>
                    </el-form-item>
                    <el-button
                      type="primary"
                      @click="save_allocation('edutruleForm')"
                      style="padding: 10px 20px; margin: 10px"
                      >保存</el-button
                    >
                    <el-button
                      type="info"
                      @click="save_resetForm('edutruleForm')"
                      style="
                        padding: 10px 20px;
                        margin: 5px;
                        margin-right: 60px;
                      "
                      >重置</el-button
                    >
                  </el-form>
                </el-drawer>
                <!-- 批量权限--对话框 -->
                <el-dialog
                  title="批量权限"
                  :visible.sync="drawerallocation"
                  width="30%"
                >
                  <el-form
                    :model="allocationruleForm"
                    ref="allocationruleForm"
                    label-width="100px"
                    class="demo-ruleForm"
                  >
                    <el-form-item label="权限名称:" prop="allocation_role_name">
                      <span>{{ allocationruleForm.allocation_role_name }}</span>
                    </el-form-item>

                    <el-form-item label="权限ID:" prop="allocation_role_id">
                      <span>{{ allocationruleForm.allocation_role_id }}</span>
                    </el-form-item>

                    <el-form-item label="选择权限" prop="allocations">
                      <el-input
                        v-model="allocationruleForm.allocations"
                        placeholder="请输权限名"
                        @change="allocation_search_fun"
                      ></el-input>
                    </el-form-item>
                    <!-- 列表--权限 -->
                    <el-table
                      :data="list_data"
                      @selection-change="handleSelectionChange_allocation"
                      ref="multipleTable"
                      border
                      style="width: 100%; margin: 20px auto"
                    >
                      <el-table-column label="全选" type="selection" width="55">
                      </el-table-column>
                      <el-table-column prop="name" label="角色名称" width="200">
                      </el-table-column>
                      <el-table-column
                        prop="description"
                        label="角色描述"
                        width="180"
                      >
                      </el-table-column>
                    </el-table>
                    <!-- 页码 -->
                    <div class="block" style="max-width: 600px; margin: auto">
                      <el-pagination
                        :page-sizes="[5, 10, 15, 20]"
                        :page-size="pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total_roles"
                        @size-change="handleChangeSize_quanxian"
                        @current-change="handleCurrentChange_quanxian"
                      >
                      </el-pagination>
                    </div>
                  </el-form>
                  <div slot="footer" class="dialog-footer">
                    <el-button
                      type="primary"
                      @click="allocationrole()"
                      style="padding: 10px 20px; margin: 10px"
                      >保 存</el-button
                    >
                    <el-button
                      @click="drawerallocation = false"
                      style="padding: 10px 20px; margin: 10px"
                      >取 消</el-button
                    >
                  </div>
                </el-dialog>
              </template>
            </el-table-column>
          </el-table>
          <div class="piliang" style="width: 95%">
            <el-button
              type="danger"
              @click="batchDelete"
              style="padding: 10px 10px"
              >批量删除</el-button
            >
            <el-button
              @click="toggleSelection()"
              type="primary"
              style="padding: 10px 10px"
              >取消选择</el-button
            >
          </div>
          <!-- 页码--主页--权限页面主页面---底部的--- -->
          <div class="block" style="max-width: 600px; margin: auto">
            <el-pagination
              :page-sizes="[5, 10, 15, 20]"
              :page-size="allocation_pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="allocation_total"
              @size-change="handleChangeSize"
              @current-change="handleCurrentChange"
            >
            </el-pagination>
          </div>
        </template>
      </XPannel>
    </el-container>
  </div>
</template>

<script>
import http from "@/api/http";
import BreadHeader from "@/components/BreadHeader.vue";
import XPannel from "@/components/XPannel.vue";
import { mapState } from "vuex";

export default {
  components: {
    XPannel,
    BreadHeader
  },
  computed: {
    ...mapState(["name","picture"]),
    userName() {
      return this.name;
    },
    userPicture() {
      return this.picture;
    },
    uniqueArray() {
      const unique = new Set(this.selected_allocation_id);
      return [...unique];
    },
  },
  data() {
    return {
      draweradd: false,
      // 添加--抽屉数据
      addruleForm: {
        addname: "",
        level: "",
        father: "",
        adddescription: "",
      },
      rulesadd: {
        addname: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        adddescription: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          { min: 2, message: "长度应大于2个字符", trigger: "blur" },
        ],
        level: [{ required: true, message: "请选择层级", trigger: "change" }],
        father: [{ required: true, message: "请选择父级", trigger: "change" }],
      },
      // 编辑--抽屉数据
      edutruleForm: {
        name: "",
        level: "",
        father: "",
        descriptionsave: "",
      },
      rulesedit: {
        name: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        descriptionsave: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          { min: 2, message: "长度应大于2个字符", trigger: "blur" },
        ],
        level: [{ required: true, message: "请选择层级", trigger: "change" }],
        father: [{ required: true, message: "请选择父级", trigger: "change" }],
      },
      searchname: "",
      allocation_list: [],
      list_data: [],
      total_roles: 0, //总数
      pageSize: 5, //每页条数
      pageNum: 1, //当前页码
      allocation_total: 0, //总数
      allocation_pageSize: 5, //每页条数
      allocation_pageNum: 1, //当前页码

      options: [
        {
          value: 1,
          level: "1级",
          father: "用户管理",
        },
        {
          value: 2,
          level: "2级",
          father: "维修管理",
        },
        {
          value: 3,
          level: "3级",
          father: "权限管理",
        },
      ],
      delroleid: null,
      xiugaiobtainuid: null,
      drawer: false, //编辑参数
      // 分配权限的数据和规范
      allocationruleForm: {
        // 分配的角色信息
        allocation_role_name: "",
        allocation_role_id: "",
        allocations: "",
      },
      drawerallocation: false,
      selected_allocation_id: [],
      allocation_index: null,
    };
  },
  methods: {
    // 列表方法及接口--角色
    listfun() {
      http
        .get("/permission/roles_list", {
          params: {
            page: this.pageNum,
            page_size: this.pageSize,
          },
        })
        .then((response) => {
          console.log(response);
          this.list_data = response.data.list;
          this.total_roles = response.data.totalNum;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 保存设置--权限支配--ing
    allocationrole() {
      http
        .post("/permission/permissions_dominate_PL/" + this.allocation_index, {
          // 一个权限对应多个角色
          allocations: this.allocationruleForm.allocation_role_id, // 多个id组成的一个数组
          allocation_role: this.allocationruleForm.allocations, // 一个权限id
        })
        .then((response) => {
          console.log(response);
          this.drawerallocation = false;
          this.allocationruleForm.allocations = null;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 批量授权按钮里面的-----搜索查询
    allocation_search_fun() {
      http
        .get("/permission/roles_search", {
          params: {
            name: this.allocationruleForm.allocations,
          },
        })
        .then((response) => {
          console.log(response);
          this.list_data = response.data;
          this.allocationruleForm.allocations = "";
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 勾选单选框的事件
    handleSelectionChange_allocation(val) {
      console.log(val);
      for (let i = 0; i < val.length; i++) {
        this.selected_allocation_id.push(val[i].id);
      }
    },
    // 批量授权按钮
    // 批量授权--按钮
    authorize(scope) {
      console.log(scope);
      console.log(scope.row.id);
      console.log(scope.$index);
      this.drawerallocation = true;
      this.allocationruleForm.allocation_role_id = scope.row.id;
      this.allocationruleForm.allocation_role_name = scope.row.name;
      let index = scope.$index + 1;
      this.allocation_index = index;
    },
    // 列表方法
    handleSelectionChange(val) {
      this.selected = val;
      console.log(this.selected);
    },
    // 搜索方法+接口--最外层的
    searchroles() {
      http
        .get("permission/permissions_search", {
          params: {
            name: this.searchname.replace(/\s+/g, ""),
            page: this.allocation_pageNum,
            page_size: this.allocation_pageSize,
          },
        })
        .then((response) => {
          console.log(response);
          this.allocation_list = response.data;
          this.allocation_total = response.total;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 权限列表方法+接口
    allocation_list_fun() {
      http
        .get("permission/permissions_list", {
          params: {
            page: this.allocation_pageNum,
            page_size: this.allocation_pageSize,
          },
        })
        .then((response) => {
          console.log(response);
          this.allocation_list = response.data.list;
          this.allocation_total = response.data.totalNum;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 添加权限的方法+接口
    addallocation() {
      http
        .post("permission/permissions_add", {
          name: this.addruleForm.addname,
          level: this.addruleForm.level,
          father: this.addruleForm.father,
          description: this.addruleForm.adddescription,
        })
        .then((response) => {
          console.log(response);
          this.allocation_list_fun();
          this.draweradd = false;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 重置添加--抽屉
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    save_resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 修改--获取数据
    xiugaiobtain(row) {
      this.drawer = true;
      console.log(row.id);
      let editid = row.id;
      http
        .get("permission/permissions_users_edit/" + editid)
        .then((response) => {
          console.log(response);
          this.xiugaiobtainuid = response.data[0].id;
          this.edutruleForm.name = response.data[0].name;
          this.edutruleForm.level = response.data[0].level;
          this.edutruleForm.father = response.data[0].father;
          this.edutruleForm.descriptionsave = response.data[0].description;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 修改--保存数据
    save_allocation(edutruleForm) {
      this.$refs[edutruleForm].validate((valid) => {
        if (valid) {
          this.$message({
            message: "恭喜你，权限修改成功！",
            type: "success",
          });
          http
            .post("permission/permissions_save_edit/" + this.xiugaiobtainuid, {
              name: this.edutruleForm.name,
              description: this.edutruleForm.descriptionsave,
              level: this.edutruleForm.level,
              father: this.edutruleForm.father,
            })
            .then((response) => {
              console.log(response);
              this.allocation_list_fun();
              this.drawer = false;
            })
            .catch((error) => {
              console.log(error);
            });
          this.drawer = false;
        } else {
          console.log("修改失败!!");
          return false;
        }
      });
    },
    // 单个删除-接口
    deleterolefn() {
      http
        .get("/permission/permissions_delete/" + this.delroleid)
        .then((response) => {
          console.log(response);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 删除按钮
    open(row) {
      this.$confirm("此操作将永久删除该权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log(1, row);
          // this.delroleid = this.userlist[row].id
          this.delroleid = row.id;
          this.deleterolefn();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.allocation_list_fun();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 批量删除按钮
    batchDelete() {
      if (this.selected.length === 0) {
        this.$message({
          message: "请先选择要删除的项",
          type: "warning",
        });
        return;
      }
      this.$confirm("此操作将永久删除选中的权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 批量删除---代办--ok
          this.selected.forEach((item) => {
            // const index = this.userlist.indexOf(item);
            let deluserids = [];
            deluserids.push(item.id);
            let deluseridsting = JSON.stringify(deluserids);
            http
              .get("/permission/permissions_deletes/" + deluseridsting)
              .then((response) => {
                console.log(response);
              })
              .catch((error) => {
                console.log(error);
              });
            this.allocation_list_fun();
            // this.userlist.splice(index, 1);
          });
          this.selected = []; // 清空选中的项
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 批量取消方法
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    // 页码设置
    // 主页的
    handleChangeSize(data) {
      this.allocation_pageSize = data;
      const isSearchnameDefault = this.searchname === "";

      if (isSearchnameDefault) {
        // 如果searchname是初始值，则调用allocation_list_fun
        this.allocation_list_fun();
      } else {
        // 否则，调用searchroles
        this.searchroles();
      }
    },
    handleChangeSize_quanxian(data) {
      this.allocation_pageSize = data;
      this.listfun();
    },
    // 主页的
    handleCurrentChange(data) {
      this.allocation_pageNum = data;
      const isSearchnameDefault = this.searchname === "";

      if (isSearchnameDefault) {
        // 如果searchname是初始值，则调用allocation_list_fun
        this.allocation_list_fun();
      } else {
        // 否则，调用searchroles
        this.searchroles();
      }
    },
    handleCurrentChange_quanxian(data) {
      this.allocation_pageNum = data;
      this.listfun();
    },
  },
  created() {
    this.allocation_list_fun();
    this.listfun();
  },
  watch: {
    selected_allocation_id() {
      // 将数组转换为字符串，并赋值给 allocationruleForm.allocations
      // 如果 allocationruleForm.allocations 需要是一个数组，就不要使用 toString 或 join
      this.allocationruleForm.allocations = this.uniqueArray.join(",");
    },
  },
};
</script>

<style scoped>
.el-form-item {
  margin-bottom: 5px;
}
</style>